package com.common;

import com.common.util.ApplicationContextUtil;
import com.hzyzt.user.dto.UserDto;
import com.hzyzt.login.dto.UserRoleDtoKey;
import com.hzyzt.user.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.jdbc.JdbcRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.ArrayList;
import java.util.List;


/**
 * @Description :
 * @Author : 吴书新
 * @Date : 2017/1/24 0024 13:51
 */
public class CustomRealm  extends JdbcRealm{

    private UserService userService;


    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        UsernamePasswordToken tokenU = new UsernamePasswordToken(
                upToken.getUsername(), String.copyValueOf(upToken
                .getPassword()), false);
        AuthenticationInfo info = super.doGetAuthenticationInfo(tokenU);
        return info;

        //userService = ApplicationContextUtil.getBean(UserService.class);
        // token中包含用户输入的用户名和密码
        // 第一步从token中取出用户名
        //String userName = (String) token.getPrincipal();
        // 第二步：根据用户输入的userCode从数据库查询
        /*UserDto user = null;
        try {
            user = userService.getUserByUserName(userName);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        // 如果查询不到返回null
        /*if (user == null) {
            return null;
        }*/
        // 获取数据库中的密码
        //String password = user.getUserPassword();
        /**
         * 认证的用户,正确的密码
         */
        //AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user, password, this.getName());
        //MD5 加密+加盐+多次加密
//<span style="color:#ff0000;">SimpleAuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password,ByteSource.Util.bytes(salt), this.getName());</span>
//        return authcInfo;
    }

    /**
     * 授权,只有成功通过<span style="font-family: Arial, Helvetica, sans-serif;">doGetAuthenticationInfo方法的认证后才会执行。</span>
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        userService = ApplicationContextUtil.getBean(UserService.class);
        // 从 principals获取主身份信息
        // 将getPrimaryPrincipal方法返回值转为真实身份类型（在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型），
        UserDto user = (UserDto) principals.getPrimaryPrincipal();
        // 根据身份信息获取权限信息
        // 从数据库获取到权限数据
        UserRoleDtoKey adminRoles = userService.getUserRoles(user);
        // 单独定一个集合对象
        List<String> permissions = new ArrayList<String>();
        if (adminRoles != null) {
            permissions.add(adminRoles.getRoleName());
        }
        // 查到权限数据，返回授权信息(要包括 上边的permissions)
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 将上边查询到授权信息填充到simpleAuthorizationInfo对象中
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    // 清除缓存
    public void clearCached() {
        PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }
}
